import React, { useEffect, useImperativeHandle } from 'react';
import { Field, Form, Input, Radio } from '@alifd/next';

function Operation(props, ref) {
  const { actionType } = props;
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const dataSource = props.dataSource || {};
  const field = Field.useField([]);
  useEffect(() => {
    field.reset();
    let newValues = {};
    if (Object.keys(dataSource).length > 0) {
      newValues = {
        jobId: dataSource.jobId,
        beanName: dataSource.beanName,
        params: dataSource.params,
        cronExpression: dataSource.cronExpression,
        status: dataSource.status,
        remark: dataSource.remark,
        createTime: dataSource.createTime,
      };
    } else {
      newValues = { status: 0 };
    }
    field.setValues(newValues);
  }, [field, dataSource]);
  useImperativeHandle(ref, () => {
    return {
      getValues(callback) {
        field.validate((errors, values) => {
          if (errors) {
            return;
          }

          callback(values);
        });
      },
    };
  });
  const isPreview = actionType === 'preview';
  return (
    <Form
      isPreview={isPreview}
      fullWidth
      useLabelForErrorMessage
      field={field}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
    >
      <Form.Item label="bean名称" required={!isPreview}>
        <Input name="beanName" autoComplete="off" placeholder="spring bean名称, 如: testTask" />
      </Form.Item>
      <Form.Item label="参数">
        <Input name="params" />
      </Form.Item>
      <Form.Item label="cron表达式" required={!isPreview}>
        <Input name="cronExpression" autoComplete="off" placeholder="如: 0 0 12 * * ?" />
      </Form.Item>
      <Form.Item label="备注">
        <Input name="remark" />
      </Form.Item>
      {isPreview ? (
        <>
          <Form.Item label="状态" required={!isPreview}>
            <Radio.Group
              name="status"
              dataSource={[
                { label: '正常', value: 0 },
                { label: '暂停', value: 1 },
              ]}
            />
          </Form.Item>
          <Form.Item label="创建时间">
            <Input name="createTime" />
          </Form.Item>
        </>
      ) : null}
    </Form>
  );
}

export default React.forwardRef(Operation);
